﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Configuration;
using Esb.Domain.Factories;
using Esb.Domain.DTO;
using Esb.Domain.DomainObjects;

namespace Esb.Soa.Domain.Monitor
{

    public class MailInfo
    {
        public string subject = "";
        public string content = "";
        public string accept;//接收
        public string cc = "";//抄送
        public string bcc = "";//暗送
        public const string sys = "Esb";//发送者
        public const string priority = "2";//等级
    }

    /// <summary>
    /// 监控同样有7*24运行要求
    /// </summary>
    public class ServiceAlert : DispatcherBase
    {
        /// <summary>
        /// 发送告警邮件
        /// </summary>
        public void SendAlertEmail(MailInfo mail)
        {
            //MailServicePortTypeClient client = new MailServicePortTypeClient();
            //client.sendEmail(mail.subject, mail.content, mail.accept, mail.cc, mail.bcc,
            //    MailInfo.sys, MailInfo.priority);
            //TODO:
        }

        /// <summary>
        /// 服务唤醒时即执行心跳
        /// </summary>
        static ServiceAlert()
        {
            /*
            ServiceAlert alert = new ServiceAlert();
            Thread thread = new Thread(new ThreadStart(() =>
                {
                    alert.HeartBeat();
                }
            ));
            thread.Start();
             */

            //ServiceAlert alert = new ServiceAlert();
            //alert.Start();//启动
        }

        public ServiceAlert()
        {
            
        }

        private string logUrl = "";//ConfigurationManager.AppSettings["logQueryUrl"];

        /// <summary>
        /// 执行时间间隔
        /// </summary>
        protected override long Interval
        {
            get { return 60000; }
        }

        /// <summary>
        /// 是否忽略异常
        /// </summary>
        protected bool IsIgnoreException
        {
            get { return true; }
        }

        protected override bool IsStartImmediate
        {
            get { return true; }
        }

        protected override void Dispatch()
        {
            try
            {
                CheckServiceStatus();
            }
            catch(Exception e)
            {
                //屏蔽异常，一直执行
                if (!IsIgnoreException)
                {
                    throw e;
                }
            }
        }

        /*
        /// <summary>
        /// 心跳，每分钟执行一次
        /// </summary>
        public void HeartBeat()
        {
            while (true)
            {
                try
                {
                    CheckServiceStatus();
                }
                catch
                {
                    //屏蔽异常，一直执行
                }
                finally
                {
                    Thread.Sleep(60000);//可配置
                }
            }
        }
         */

        /// <summary>
        /// 检查服务状态
        /// </summary>
        public void CheckServiceStatus()
        {
            //所有注册的服务
            ServiceFactory factory = new ServiceFactory();
            QueryCondition condition = new QueryCondition();
            List<ServiceDo> svcs = factory.GetServicesByCondition(condition);

            //TODO:过去的逻辑，会发生重复发邮件情况，还没处理
            /*

            //根据名字拉取服务log的数据
            QueryAppLogRequest logRequest = new QueryAppLogRequest();
            logRequest.AppId = ConfigurationManager.AppSettings["AppId"];
            logRequest.FromTime = DateTime.Now.AddMinutes(-15).ToString();
            logRequest.ToTime = DateTime.Now.ToString();
            logRequest.Level = LogLevelTypeEnum.Info;
            logRequest.ClassName = "Esb Error";
            logRequest.PageSize = int.MaxValue;
            logRequest.Page = 1;

            RestServiceHandler rest = new RestServiceHandler();
            string logRequest2 = Helper.Serialize(logRequest);
            string response = rest.ProcessCallService(logRequest2, logUrl, "QueryAppLog");
            QueryAppLogResponse response2 = Helper.Deserialize<QueryAppLogResponse>(response);

            //检查标准:同一服务，在过去的15分钟内，连续出现5次异常，可配置，暂写死
            Dictionary<string, int> logs = new Dictionary<string, int>();
            foreach (AppLogDTO log in response2.AppLogs)
            {
                string[] logAppInfos = log.MethodName.Split(new string[] { " - " }, StringSplitOptions.RemoveEmptyEntries);
                string logAppId = logAppInfos[1];
                if (!logs.ContainsKey(log.AppId))
                    logs[logAppId] = 0;

                int count = logs[logAppId] += 1;
                ServiceDo svc = svcs.FirstOrDefault(s => s.AppId.ToString() == logAppId);
                if (count >= svc.AlertNumber)
                {
                    MailInfo mail = new MailInfo();
                    mail.subject = log.ClassName;
                    mail.content = log.MethodName;
                    mail.accept = svc.AlertMail;//服务注册的告警邮件地址
                    //mail.content += "<br />" + log.Content;
                    SendAlertEmail(mail);
                }
            }

            Logger.Info("Esb Monitor", "",  "");
             */
        }
    }
}
